using System;
using DNT.RavenQA.Core.Extensions;
using DNT.RavenQA.Core.Models;
using Raven.Client;

namespace DNT.RavenQA.Web.ViewModels
{
    public class UserInfo : IEquatable<UserInfo>
    {
        public Boolean Equals(UserInfo other)
        {
            if (ReferenceEquals(null, other)) 
                return false;

            if (ReferenceEquals(this, other)) 
                return true;

            return UserId == other.UserId;
        }

        public override Int32 GetHashCode()
        {
            return UserId;
        }

        public static Boolean operator ==(UserInfo left, UserInfo right)
        {
            return Equals(left, right);
        }

        public static Boolean operator !=(UserInfo left, UserInfo right)
        {
            return !Equals(left, right);
        }

        public static UserInfo Build(IDocumentSession session, Contribute contribute)
        {
            session.EnsureIsNotNull("session");
            contribute.EnsureIsNotNull("contribute");

            var user = session.Load<User>(contribute.User.Id);

            if (user.IsNull())
                throw new NonExistingUserException(String.Format("Cannot find a used with id '{0}'.", contribute.User.Id));

            return new UserInfo
                       {
                           UserId = user.Key,
                           UserName = user.Name,
                           ContributionsCount = user.ContributionsCount,
                           GravatarUrl = user.GravatarUrl
                       };
        }

        public static UserInfo Build(User user)
        {
            user.EnsureIsNotNull("user");

            return new UserInfo
            {
                UserId = user.Key,
                UserName = user.Name,
                ContributionsCount = user.ContributionsCount,
                GravatarUrl = user.GravatarUrl
            };
        }

        public Int32 UserId { get; private set; }
        public String UserName { get; private set; }
        public Int32 ContributionsCount { get; private set; }
        public String GravatarUrl { get; private set; }

        public override Boolean Equals(Object obj)
        {
            var userInfo = obj as UserInfo;
            return userInfo != null ? Equals(userInfo) : base.Equals(obj);
        }
    }
}